home *** CD-ROM | disk | FTP | other *** search
/ Aminet 40 / Aminet 40 (2000)(Schatztruhe)[!][Dec 2000].iso / Aminet / dev / lang / Python16_Src.lha / Python16_Source / Objects / classobject.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-09-10  |  37.8 KB  |  1,677 lines

  1. /* Class object implementation */
  2.  
  3. #include "Python.h"
  4. #include "structmember.h"
  5. #include "protos/classobject.h"
  6.  
  7. /* Forward */
  8. static PyObject *class_lookup
  9.     Py_PROTO((PyClassObject *, PyObject *, PyClassObject **));
  10. static PyObject *instance_getattr1 Py_PROTO((PyInstanceObject *, PyObject *));
  11. static PyObject *instance_getattr2 Py_PROTO((PyInstanceObject *, PyObject *));
  12.  
  13. static PyObject *getattrstr, *setattrstr, *delattrstr;
  14.  
  15. PyObject *
  16. PyClass_New(bases, dict, name)
  17.     PyObject *bases; /* NULL or tuple of classobjects! */
  18.     PyObject *dict;
  19.     PyObject *name;
  20. {
  21.     PyClassObject *op, *dummy;
  22.     static PyObject *docstr, *modstr, *namestr;
  23.     if (docstr == NULL) {
  24.         docstr= PyString_InternFromString("__doc__");
  25.         if (docstr == NULL)
  26.             return NULL;
  27.     }
  28.     if (modstr == NULL) {
  29.         modstr= PyString_InternFromString("__module__");
  30.         if (modstr == NULL)
  31.             return NULL;
  32.     }
  33.     if (namestr == NULL) {
  34.         namestr= PyString_InternFromString("__name__");
  35.         if (namestr == NULL)
  36.             return NULL;
  37.     }
  38.     if (name == NULL || !PyString_Check(name)) {
  39.         PyErr_SetString(PyExc_SystemError,
  40.                 "PyClass_New: name must be a string");
  41.         return NULL;
  42.     }
  43.     if (dict == NULL || !PyDict_Check(dict)) {
  44.         PyErr_SetString(PyExc_SystemError,
  45.                 "PyClass_New: dict must be a dictionary");
  46.         return NULL;
  47.     }
  48.     if (PyDict_GetItem(dict, docstr) == NULL) {
  49.         if (PyDict_SetItem(dict, docstr, Py_None) < 0)
  50.             return NULL;
  51.     }
  52.     if (PyDict_GetItem(dict, modstr) == NULL) {
  53.         PyObject *globals = PyEval_GetGlobals();
  54.         if (globals != NULL) {
  55.             PyObject *modname = PyDict_GetItem(globals, namestr);
  56.             if (modname != NULL) {
  57.                 if (PyDict_SetItem(dict, modstr, modname) < 0)
  58.                     return NULL;
  59.             }
  60.         }
  61.     }
  62.     if (bases == NULL) {
  63.         bases = PyTuple_New(0);
  64.         if (bases == NULL)
  65.             return NULL;
  66.     }
  67.     else {
  68.         int i;
  69.         if (!PyTuple_Check(bases)) {
  70.             PyErr_SetString(PyExc_SystemError,
  71.                     "PyClass_New: bases must be a tuple");
  72.             return NULL;
  73.         }
  74.         i = PyTuple_Size(bases);
  75.         while (--i >= 0) {
  76.             if (!PyClass_Check(PyTuple_GetItem(bases, i))) {
  77.                 PyErr_SetString(PyExc_SystemError,
  78.                     "PyClass_New: base must be a class");
  79.                 return NULL;
  80.             }
  81.         }
  82.         Py_INCREF(bases);
  83.     }
  84.     op = PyObject_NEW(PyClassObject, &PyClass_Type);
  85.     if (op == NULL) {
  86.         Py_DECREF(bases);
  87.         return NULL;
  88.     }
  89.     op->cl_bases = bases;
  90.     Py_INCREF(dict);
  91.     op->cl_dict = dict;
  92.     Py_XINCREF(name);
  93.     op->cl_name = name;
  94.     if (getattrstr == NULL) {
  95.         getattrstr = PyString_InternFromString("__getattr__");
  96.         setattrstr = PyString_InternFromString("__setattr__");
  97.         delattrstr = PyString_InternFromString("__delattr__");
  98.     }
  99.     op->cl_getattr = class_lookup(op, getattrstr, &dummy);
  100.     op->cl_setattr = class_lookup(op, setattrstr, &dummy);
  101.     op->cl_delattr = class_lookup(op, delattrstr, &dummy);
  102.     Py_XINCREF(op->cl_getattr);
  103.     Py_XINCREF(op->cl_setattr);
  104.     Py_XINCREF(op->cl_delattr);
  105.     return (PyObject *) op;
  106. }
  107.  
  108. /* Class methods */
  109.  
  110. static void
  111. class_dealloc(op)
  112.     PyClassObject *op;
  113. {
  114.     Py_DECREF(op->cl_bases);
  115.     Py_DECREF(op->cl_dict);
  116.     Py_XDECREF(op->cl_name);
  117.     Py_XDECREF(op->cl_getattr);
  118.     Py_XDECREF(op->cl_setattr);
  119.     Py_XDECREF(op->cl_delattr);
  120.     PyObject_DEL(op);
  121. }
  122.  
  123. static PyObject *
  124. class_lookup(cp, name, pclass)
  125.     PyClassObject *cp;
  126.     PyObject *name;
  127.     PyClassObject **pclass;
  128. {
  129.     int i, n;
  130.     PyObject *value = PyDict_GetItem(cp->cl_dict, name);
  131.     if (value != NULL) {
  132.         *pclass = cp;
  133.         return value;
  134.     }
  135.     n = PyTuple_Size(cp->cl_bases);
  136.     for (i = 0; i < n; i++) {
  137.         /* XXX What if one of the bases is not a class? */
  138.         PyObject *v = class_lookup(
  139.             (PyClassObject *)
  140.             PyTuple_GetItem(cp->cl_bases, i), name, pclass);
  141.         if (v != NULL)
  142.             return v;
  143.     }
  144.     return NULL;
  145. }
  146.  
  147. static PyObject *
  148. class_getattr(op, name)
  149.     register PyClassObject *op;
  150.     PyObject *name;
  151. {
  152.     register PyObject *v;
  153.     register char *sname = PyString_AsString(name);
  154.     PyClassObject *class;
  155.     if (sname[0] == '_' && sname[1] == '_') {
  156.         if (strcmp(sname, "__dict__") == 0) {
  157.             if (PyEval_GetRestricted()) {
  158.                 PyErr_SetString(PyExc_RuntimeError,
  159.                "class.__dict__ not accessible in restricted mode");
  160.                 return NULL;
  161.             }
  162.             Py_INCREF(op->cl_dict);
  163.             return op->cl_dict;
  164.         }
  165.         if (strcmp(sname, "__bases__") == 0) {
  166.             Py_INCREF(op->cl_bases);
  167.             return op->cl_bases;
  168.         }
  169.         if (strcmp(sname, "__name__") == 0) {
  170.             if (op->cl_name == NULL)
  171.                 v = Py_None;
  172.             else
  173.                 v = op->cl_name;
  174.             Py_INCREF(v);
  175.             return v;
  176.         }
  177.     }
  178.     v = class_lookup(op, name, &class);
  179.     if (v == NULL) {
  180.         PyErr_SetObject(PyExc_AttributeError, name);
  181.         return NULL;
  182.     }
  183.     Py_INCREF(v);
  184.     if (PyFunction_Check(v)) {
  185.         PyObject *w = PyMethod_New(v, (PyObject *)NULL,
  186.                             (PyObject *)class);
  187.         Py_DECREF(v);
  188.         v = w;
  189.     }
  190.     return v;
  191. }
  192.  
  193. static void
  194. set_slot(slot, v)
  195.     PyObject **slot;
  196.     PyObject *v;
  197. {
  198.     PyObject *temp = *slot;
  199.     Py_XINCREF(v);
  200.     *slot = v;
  201.     Py_XDECREF(temp);
  202. }
  203.  
  204. static void
  205. set_attr_slots(c)
  206.     PyClassObject *c;
  207. {
  208.     PyClassObject *dummy;
  209.  
  210.     set_slot(&c->cl_getattr, class_lookup(c, getattrstr, &dummy));
  211.     set_slot(&c->cl_setattr, class_lookup(c, setattrstr, &dummy));
  212.     set_slot(&c->cl_delattr, class_lookup(c, delattrstr, &dummy));
  213. }
  214.  
  215. static char *
  216. set_dict(c, v)
  217.     PyClassObject *c;
  218.     PyObject *v;
  219. {
  220.     if (v == NULL || !PyDict_Check(v))
  221.         return "__dict__ must be a dictionary object";
  222.     set_slot(&c->cl_dict, v);
  223.     set_attr_slots(c);
  224.     return "";
  225. }
  226.  
  227. static char *
  228. set_bases(c, v)
  229.     PyClassObject *c;
  230.     PyObject *v;
  231. {
  232.     int i, n;
  233.  
  234.     if (v == NULL || !PyTuple_Check(v))
  235.         return "__bases__ must be a tuple object";
  236.     n = PyTuple_Size(v);
  237.     for (i = 0; i < n; i++) {
  238.         PyObject *x = PyTuple_GET_ITEM(v, i);
  239.         if (!PyClass_Check(x))
  240.             return "__bases__ items must be classes";
  241.         if (PyClass_IsSubclass(x, (PyObject *)c))
  242.             return "a __bases__ item causes an inheritance cycle";
  243.     }
  244.     set_slot(&c->cl_bases, v);
  245.     set_attr_slots(c);
  246.     return "";
  247. }
  248.  
  249. static char *
  250. set_name(c, v)
  251.     PyClassObject *c;
  252.     PyObject *v;
  253. {
  254.     if (v == NULL || !PyString_Check(v))
  255.         return "__name__ must be a string object";
  256.     if ((long)strlen(PyString_AS_STRING(v)) != PyString_GET_SIZE(v))
  257.         return "__name__ must not contain null bytes";
  258.     set_slot(&c->cl_name, v);
  259.     return "";
  260. }
  261.  
  262. static int
  263. class_setattr(op, name, v)
  264.     PyClassObject *op;
  265.     PyObject *name;
  266.     PyObject *v;
  267. {
  268.     char *sname;
  269.     if (PyEval_GetRestricted()) {
  270.         PyErr_SetString(PyExc_RuntimeError,
  271.                "classes are read-only in restricted mode");
  272.         return -1;
  273.     }
  274.     sname = PyString_AsString(name);
  275.     if (sname[0] == '_' && sname[1] == '_') {
  276.         int n = PyString_Size(name);
  277.         if (sname[n-1] == '_' && sname[n-2] == '_') {
  278.             char *err = NULL;
  279.             if (strcmp(sname, "__dict__") == 0)
  280.                 err = set_dict(op, v);
  281.             else if (strcmp(sname, "__bases__") == 0)
  282.                 err = set_bases(op, v);
  283.             else if (strcmp(sname, "__name__") == 0)
  284.                 err = set_name(op, v);
  285.             else if (strcmp(sname, "__getattr__") == 0)
  286.                 set_slot(&op->cl_getattr, v);
  287.             else if (strcmp(sname, "__setattr__") == 0)
  288.                 set_slot(&op->cl_setattr, v);
  289.             else if (strcmp(sname, "__delattr__") == 0)
  290.                 set_slot(&op->cl_delattr, v);
  291.             /* For the last three, we fall through to update the
  292.                dictionary as well. */
  293.             if (err != NULL) {
  294.                 if (*err == '\0')
  295.                     return 0;
  296.                 PyErr_SetString(PyExc_TypeError, err);
  297.                 return -1;
  298.             }
  299.         }
  300.     }
  301.     if (v == NULL) {
  302.         int rv = PyDict_DelItem(op->cl_dict, name);
  303.         if (rv < 0)
  304.             PyErr_SetString(PyExc_AttributeError,
  305.                    "delete non-existing class attribute");
  306.         return rv;
  307.     }
  308.     else
  309.         return PyDict_SetItem(op->cl_dict, name, v);
  310. }
  311.  
  312. static PyObject *
  313. class_repr(op)
  314.     PyClassObject *op;
  315. {
  316.     PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
  317.     char buf[140];
  318.     char *name;
  319.     if (op->cl_name == NULL || !PyString_Check(op->cl_name))
  320.         name = "?";
  321.     else
  322.         name = PyString_AsString(op->cl_name);
  323.     if (mod == NULL || !PyString_Check(mod))
  324.         sprintf(buf, "<class ?.%.100s at %lx>", name, (long)op);
  325.     else
  326.         sprintf(buf, "<class %.50s.%.50s at %lx>",
  327.             PyString_AsString(mod),
  328.             name, (long)op);
  329.     return PyString_FromString(buf);
  330. }
  331.  
  332. static PyObject *
  333. class_str(op)
  334.     PyClassObject *op;
  335. {
  336.     PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
  337.     PyObject *name = op->cl_name;
  338.     PyObject *res;
  339.     int m, n;
  340.  
  341.     if (name == NULL || !PyString_Check(name))
  342.         return class_repr(op);
  343.     if (mod == NULL || !PyString_Check(mod)) {
  344.         Py_INCREF(name);
  345.         return name;
  346.     }
  347.     m = PyString_Size(mod);
  348.     n = PyString_Size(name);
  349.     res = PyString_FromStringAndSize((char *)NULL, m+1+n);
  350.     if (res != NULL) {
  351.         char *s = PyString_AsString(res);
  352.         memcpy(s, PyString_AsString(mod), m);
  353.         s += m;
  354.         *s++ = '.';
  355.         memcpy(s, PyString_AsString(name), n);
  356.     }
  357.     return res;
  358. }
  359.  
  360. PyTypeObject PyClass_Type = {
  361.     PyObject_HEAD_INIT(&PyType_Type)
  362.     0,
  363.     "class",
  364.     sizeof(PyClassObject),
  365.     0,
  366.     (destructor)class_dealloc, /*tp_dealloc*/
  367.     0,        /*tp_print*/
  368.     0,        /*tp_getattr*/
  369.     0,        /*tp_setattr*/
  370.     0,        /*tp_compare*/
  371.     (reprfunc)class_repr, /*tp_repr*/
  372.     0,        /*tp_as_number*/
  373.     0,        /*tp_as_sequence*/
  374.     0,        /*tp_as_mapping*/
  375.     0,        /*tp_hash*/
  376.     0,        /*tp_call*/
  377.     (reprfunc)class_str, /*tp_str*/
  378.     (getattrofunc)class_getattr, /*tp_getattro*/
  379.     (setattrofunc)class_setattr, /*tp_setattro*/
  380. };
  381.  
  382. int
  383. PyClass_IsSubclass(class, base)
  384.     PyObject *class;
  385.     PyObject *base;
  386. {
  387.     int i, n;
  388.     PyClassObject *cp;
  389.     if (class == base)
  390.         return 1;
  391.     if (class == NULL || !PyClass_Check(class))
  392.         return 0;
  393.     cp = (PyClassObject *)class;
  394.     n = PyTuple_Size(cp->cl_bases);
  395.     for (i = 0; i < n; i++) {
  396.         if (PyClass_IsSubclass(PyTuple_GetItem(cp->cl_bases, i), base))
  397.             return 1;
  398.     }
  399.     return 0;
  400. }
  401.  
  402.  
  403. /* Instance objects */
  404.  
  405. PyObject *
  406. PyInstance_New(class, arg, kw)
  407.     PyObject *class;
  408.     PyObject *arg;
  409.     PyObject *kw;
  410. {
  411.     register PyInstanceObject *inst;
  412.     PyObject *init;
  413.     static PyObject *initstr;
  414.     if (!PyClass_Check(class)) {
  415.         PyErr_BadInternalCall();
  416.         return NULL;
  417.     }
  418.     inst = PyObject_NEW(PyInstanceObject, &PyInstance_Type);
  419.     if (inst == NULL)
  420.         return NULL;
  421.     Py_INCREF(class);
  422.     inst->in_class = (PyClassObject *)class;
  423.     inst->in_dict = PyDict_New();
  424.     if (inst->in_dict == NULL) {
  425.         Py_DECREF(inst);
  426.         return NULL;
  427.     }
  428.     if (initstr == NULL)
  429.         initstr = PyString_InternFromString("__init__");
  430.     init = instance_getattr2(inst, initstr);
  431.     if (init == NULL) {
  432.         if ((arg != NULL && (!PyTuple_Check(arg) ||
  433.                      PyTuple_Size(arg) != 0))
  434.             || (kw != NULL && (!PyDict_Check(kw) ||
  435.                       PyDict_Size(kw) != 0))) {
  436.             PyErr_SetString(PyExc_TypeError,
  437.                    "this constructor takes no arguments");
  438.             Py_DECREF(inst);
  439.             inst = NULL;
  440.         }
  441.     }
  442.     else {
  443.         PyObject *res = PyEval_CallObjectWithKeywords(init, arg, kw);
  444.         Py_DECREF(init);
  445.         if (res == NULL) {
  446.             Py_DECREF(inst);
  447.             inst = NULL;
  448.         }
  449.         else {
  450.             if (res != Py_None) {
  451.                 PyErr_SetString(PyExc_TypeError,
  452.                        "__init__() should return None");
  453.                 Py_DECREF(inst);
  454.                 inst = NULL;
  455.             }
  456.             Py_DECREF(res);
  457.         }
  458.     }
  459.     return (PyObject *)inst;
  460. }
  461.  
  462. /* Instance methods */
  463.  
  464. static void
  465. instance_dealloc(inst)
  466.     register PyInstanceObject *inst;
  467. {
  468.     PyObject *error_type, *error_value, *error_traceback;
  469.     PyObject *del;
  470.     static PyObject *delstr;
  471.     /* Call the __del__ method if it exists.  First temporarily
  472.        revive the object and save the current exception, if any. */
  473. #ifdef Py_TRACE_REFS
  474.     /* much too complicated if Py_TRACE_REFS defined */
  475.     extern long _Py_RefTotal;
  476.     inst->ob_type = &PyInstance_Type;
  477.     _Py_NewReference((PyObject *)inst);
  478.     _Py_RefTotal--;        /* compensate for increment in NEWREF */
  479. #ifdef COUNT_ALLOCS
  480.     inst->ob_type->tp_alloc--; /* ditto */
  481. #endif
  482. #else /* !Py_TRACE_REFS */
  483.     Py_INCREF(inst);
  484. #endif /* !Py_TRACE_REFS */
  485.     PyErr_Fetch(&error_type, &error_value, &error_traceback);
  486.     if (delstr == NULL)
  487.         delstr = PyString_InternFromString("__del__");
  488.     if ((del = instance_getattr2(inst, delstr)) != NULL) {
  489.         PyObject *res = PyEval_CallObject(del, (PyObject *)NULL);
  490.         if (res == NULL) {
  491.             PyObject *f, *t, *v, *tb;
  492.              PyErr_Fetch(&t, &v, &tb);
  493.             f = PySys_GetObject("stderr");
  494.             if (f != NULL) {
  495.                 PyFile_WriteString("Exception ", f);
  496.                 if (t) {
  497.                     PyFile_WriteObject(t, f, Py_PRINT_RAW);
  498.                     if (v && v != Py_None) {
  499.                         PyFile_WriteString(": ", f);
  500.                         PyFile_WriteObject(v, f, 0);
  501.                     }
  502.                 }
  503.                 PyFile_WriteString(" in ", f);
  504.                 PyFile_WriteObject(del, f, 0);
  505.                 PyFile_WriteString(" ignored\n", f);
  506.                 PyErr_Clear(); /* Just in case */
  507.             }
  508.             Py_XDECREF(t);
  509.             Py_XDECREF(v);
  510.             Py_XDECREF(tb);
  511.         }
  512.         else
  513.             Py_DECREF(res);
  514.         Py_DECREF(del);
  515.     }
  516.     /* Restore the saved exception and undo the temporary revival */
  517.     PyErr_Restore(error_type, error_value, error_traceback);
  518.     /* Can't use DECREF here, it would cause a recursive call */
  519.     if (--inst->ob_refcnt > 0) {
  520. #ifdef COUNT_ALLOCS
  521.         inst->ob_type->tp_free--;
  522. #endif
  523.         return; /* __del__ added a reference; don't delete now */
  524.     }
  525. #ifdef Py_TRACE_REFS
  526. #ifdef COUNT_ALLOCS
  527.     inst->ob_type->tp_free--;    /* compensate for increment in UNREF */
  528. #endif
  529.     _Py_ForgetReference((PyObject *)inst);
  530.     inst->ob_type = NULL;
  531. #endif /* Py_TRACE_REFS */
  532.     Py_DECREF(inst->in_class);
  533.     Py_XDECREF(inst->in_dict);
  534.     PyObject_DEL(inst);
  535. }
  536.  
  537. static PyObject *
  538. instance_getattr1(inst, name)
  539.     register PyInstanceObject *inst;
  540.     PyObject *name;
  541. {
  542.     register PyObject *v;
  543.     register char *sname = PyString_AsString(name);
  544.     if (sname[0] == '_' && sname[1] == '_') {
  545.         if (strcmp(sname, "__dict__") == 0) {
  546.             if (PyEval_GetRestricted()) {
  547.                 PyErr_SetString(PyExc_RuntimeError,
  548.             "instance.__dict__ not accessible in restricted mode");
  549.                 return NULL;
  550.             }
  551.             Py_INCREF(inst->in_dict);
  552.             return inst->in_dict;
  553.         }
  554.         if (strcmp(sname, "__class__") == 0) {
  555.             Py_INCREF(inst->in_class);
  556.             return (PyObject *)inst->in_class;
  557.         }
  558.     }
  559.     v = instance_getattr2(inst, name);
  560.     if (v == NULL) {
  561.         PyErr_Format(PyExc_AttributeError,"'%.50s' instance has no attribute '%.400s'",
  562.                  PyString_AS_STRING(inst->in_class->cl_name), sname);
  563.     }
  564.     return v;
  565. }
  566.  
  567. static PyObject *
  568. instance_getattr2(inst, name)
  569.     register PyInstanceObject *inst;
  570.     PyObject *name;
  571. {
  572.     register PyObject *v;
  573.     PyClassObject *class;
  574.     class = NULL;
  575.     v = PyDict_GetItem(inst->in_dict, name);
  576.     if (v == NULL) {
  577.         v = class_lookup(inst->in_class, name, &class);
  578.         if (v == NULL)
  579.             return v;
  580.     }
  581.     Py_INCREF(v);
  582.     if (class != NULL) {
  583.         if (PyFunction_Check(v)) {
  584.             PyObject *w = PyMethod_New(v, (PyObject *)inst,
  585.                                 (PyObject *)class);
  586.             Py_DECREF(v);
  587.             v = w;
  588.         }
  589.         else if (PyMethod_Check(v)) {
  590.             PyObject *im_class = PyMethod_Class(v);
  591.             /* Only if classes are compatible */
  592.             if (PyClass_IsSubclass((PyObject *)class, im_class)) {
  593.                 PyObject *im_func = PyMethod_Function(v);
  594.                 PyObject *w = PyMethod_New(im_func,
  595.                         (PyObject *)inst, im_class);
  596.                 Py_DECREF(v);
  597.                 v = w;
  598.             }
  599.         }
  600.     }
  601.     return v;
  602. }
  603.  
  604. static PyObject *
  605. instance_getattr(inst, name)
  606.     register PyInstanceObject *inst;
  607.     PyObject *name;
  608. {
  609.     register PyObject *func, *res;
  610.     res = instance_getattr1(inst, name);
  611.     if (res == NULL && (func = inst->in_class->cl_getattr) != NULL) {
  612.         PyObject *args;
  613.         PyErr_Clear();
  614.         args = Py_BuildValue("(OO)", inst, name);
  615.         if (args == NULL)
  616.             return NULL;
  617.         res = PyEval_CallObject(func, args);
  618.         Py_DECREF(args);
  619.     }
  620.     return res;
  621. }
  622.  
  623. static int
  624. instance_setattr1(inst, name, v)
  625.     PyInstanceObject *inst;
  626.     PyObject *name;
  627.     PyObject *v;
  628. {
  629.     if (v == NULL) {
  630.         int rv = PyDict_DelItem(inst->in_dict, name);
  631.         if (rv < 0)
  632.             PyErr_SetString(PyExc_AttributeError,
  633.                    "delete non-existing instance attribute");
  634.         return rv;
  635.     }
  636.     else
  637.         return PyDict_SetItem(inst->in_dict, name, v);
  638. }
  639.  
  640. static int
  641. instance_setattr(inst, name, v)
  642.     PyInstanceObject *inst;
  643.     PyObject *name;
  644.     PyObject *v;
  645. {
  646.     PyObject *func, *args, *res, *tmp;
  647.     char *sname = PyString_AsString(name);
  648.     if (sname[0] == '_' && sname[1] == '_') {
  649.         int n = PyString_Size(name);
  650.         if (sname[n-1] == '_' && sname[n-2] == '_') {
  651.             if (strcmp(sname, "__dict__") == 0) {
  652.                 if (PyEval_GetRestricted()) {
  653.                     PyErr_SetString(PyExc_RuntimeError,
  654.                  "__dict__ not accessible in restricted mode");
  655.                     return -1;
  656.                 }
  657.                 if (v == NULL || !PyDict_Check(v)) {
  658.                     PyErr_SetString(PyExc_TypeError,
  659.                        "__dict__ must be set to a dictionary");
  660.                     return -1;
  661.                 }
  662.                 tmp = inst->in_dict;
  663.                 Py_INCREF(v);
  664.                 inst->in_dict = v;
  665.                 Py_DECREF(tmp);
  666.                 return 0;
  667.             }
  668.             if (strcmp(sname, "__class__") == 0) {
  669.                 if (PyEval_GetRestricted()) {
  670.                     PyErr_SetString(PyExc_RuntimeError,
  671.                 "__class__ not accessible in restricted mode");
  672.                     return -1;
  673.                 }
  674.                 if (v == NULL || !PyClass_Check(v)) {
  675.                     PyErr_SetString(PyExc_TypeError,
  676.                        "__class__ must be set to a class");
  677.                     return -1;
  678.                 }
  679.                 tmp = (PyObject *)(inst->in_class);
  680.                 Py_INCREF(v);
  681.                 inst->in_class = (PyClassObject *)v;
  682.                 Py_DECREF(tmp);
  683.                 return 0;
  684.             }
  685.         }
  686.     }
  687.     if (v == NULL)
  688.         func = inst->in_class->cl_delattr;
  689.     else
  690.         func = inst->in_class->cl_setattr;
  691.     if (func == NULL)
  692.         return instance_setattr1(inst, name, v);
  693.     if (v == NULL)
  694.         args = Py_BuildValue("(OO)", inst, name);
  695.     else
  696.         args = Py_BuildValue("(OOO)", inst, name, v);
  697.     if (args == NULL)
  698.         return -1;
  699.     res = PyEval_CallObject(func, args);
  700.     Py_DECREF(args);
  701.     if (res == NULL)
  702.         return -1;
  703.     Py_DECREF(res);
  704.     return 0;
  705. }
  706.  
  707. static PyObject *
  708. instance_repr(inst)
  709.     PyInstanceObject *inst;
  710. {
  711.     PyObject *func;
  712.     PyObject *res;
  713.     static PyObject *reprstr;
  714.  
  715.     if (reprstr == NULL)
  716.         reprstr = PyString_InternFromString("__repr__");
  717.     func = instance_getattr(inst, reprstr);
  718.     if (func == NULL) {
  719.         char buf[140];
  720.         PyObject *classname = inst->in_class->cl_name;
  721.         PyObject *mod = PyDict_GetItemString(
  722.             inst->in_class->cl_dict, "__module__");
  723.         char *cname;
  724.         if (classname != NULL && PyString_Check(classname))
  725.             cname = PyString_AsString(classname);
  726.         else
  727.             cname = "?";
  728.         PyErr_Clear();
  729.         if (mod == NULL || !PyString_Check(mod))
  730.             sprintf(buf, "<?.%.100s instance at %lx>",
  731.                 cname, (long)inst);
  732.         else
  733.             sprintf(buf, "<%.50s.%.50s instance at %lx>",
  734.                 PyString_AsString(mod),
  735.                 cname, (long)inst);
  736.         return PyString_FromString(buf);
  737.     }
  738.     res = PyEval_CallObject(func, (PyObject *)NULL);
  739.     Py_DECREF(func);
  740.     return res;
  741. }
  742.  
  743. static PyObject *
  744. instance_compare1(inst, other)
  745.     PyObject *inst, *other;
  746. {
  747.     return PyInstance_DoBinOp(inst, other, "__cmp__", "__rcmp__",
  748.                  instance_compare1);
  749. }
  750.  
  751. static int
  752. instance_compare(inst, other)
  753.     PyObject *inst, *other;
  754. {
  755.     PyObject *result;
  756.     long outcome;
  757.     result = instance_compare1(inst, other);
  758.     if (result == NULL)
  759.         return -1;
  760.     if (!PyInt_Check(result)) {
  761.         Py_DECREF(result);
  762.         PyErr_SetString(PyExc_TypeError,
  763.                 "comparison did not return an int");
  764.         return -1;
  765.     }
  766.     outcome = PyInt_AsLong(result);
  767.     Py_DECREF(result);
  768.     if (outcome < 0)
  769.         return -1;
  770.     else if (outcome > 0)
  771.         return 1;
  772.     return 0;
  773. }
  774.  
  775. static long
  776. instance_hash(inst)
  777.     PyInstanceObject *inst;
  778. {
  779.     PyObject *func;
  780.     PyObject *res;
  781.     long outcome;
  782.     static PyObject *hashstr, *cmpstr;
  783.  
  784.     if (hashstr == NULL)
  785.         hashstr = PyString_InternFromString("__hash__");
  786.     func = instance_getattr(inst, hashstr);
  787.     if (func == NULL) {
  788.         /* If there is no __cmp__ method, we hash on the address.
  789.            If a __cmp__ method exists, there must be a __hash__. */
  790.         PyErr_Clear();
  791.         if (cmpstr == NULL)
  792.             cmpstr = PyString_InternFromString("__cmp__");
  793.         func = instance_getattr(inst, cmpstr);
  794.         if (func == NULL) {
  795.             PyErr_Clear();
  796.             outcome = (long)inst;
  797.             if (outcome == -1)
  798.                 outcome = -2;
  799.             return outcome;
  800.         }
  801.         PyErr_SetString(PyExc_TypeError, "unhashable instance");
  802.         return -1;
  803.     }
  804.     res = PyEval_CallObject(func, (PyObject *)NULL);
  805.     Py_DECREF(func);
  806.     if (res == NULL)
  807.         return -1;
  808.     if (PyInt_Check(res)) {
  809.         outcome = PyInt_AsLong(res);
  810.         if (outcome == -1)
  811.             outcome = -2;
  812.     }
  813.     else {
  814.         PyErr_SetString(PyExc_TypeError,
  815.                 "__hash__() should return an int");
  816.         outcome = -1;
  817.     }
  818.     Py_DECREF(res);
  819.     return outcome;
  820. }
  821.  
  822. static PyObject *getitemstr, *setitemstr, *delitemstr, *lenstr;
  823.  
  824. static int
  825. instance_length(inst)
  826.     PyInstanceObject *inst;
  827. {
  828.     PyObject *func;
  829.     PyObject *res;
  830.     int outcome;
  831.  
  832.     if (lenstr == NULL)
  833.         lenstr = PyString_InternFromString("__len__");
  834.     func = instance_getattr(inst, lenstr);
  835.     if (func == NULL)
  836.         return -1;
  837.     res = PyEval_CallObject(func, (PyObject *)NULL);
  838.     Py_DECREF(func);
  839.     if (res == NULL)
  840.         return -1;
  841.     if (PyInt_Check(res)) {
  842.         outcome = PyInt_AsLong(res);
  843.         if (outcome < 0)
  844.             PyErr_SetString(PyExc_ValueError,
  845.                     "__len__() should return >= 0");
  846.     }
  847.     else {
  848.         PyErr_SetString(PyExc_TypeError,
  849.                 "__len__() should return an int");
  850.         outcome = -1;
  851.     }
  852.     Py_DECREF(res);
  853.     return outcome;
  854. }
  855.  
  856. static PyObject *
  857. instance_subscript(inst, key)
  858.     PyInstanceObject *inst;
  859.     PyObject *key;
  860. {
  861.     PyObject *func;
  862.     PyObject *arg;
  863.     PyObject *res;
  864.  
  865.     if (getitemstr == NULL)
  866.         getitemstr = PyString_InternFromString("__getitem__");
  867.     func = instance_getattr(inst, getitemstr);
  868.     if (func == NULL)
  869.         return NULL;
  870.     arg = Py_BuildValue("(O)", key);
  871.     if (arg == NULL) {
  872.         Py_DECREF(func);
  873.         return NULL;
  874.     }
  875.     res = PyEval_CallObject(func, arg);
  876.     Py_DECREF(func);
  877.     Py_DECREF(arg);
  878.     return res;
  879. }
  880.  
  881. static int
  882. instance_ass_subscript(inst, key, value)
  883.     PyInstanceObject*inst;
  884.     PyObject *key;
  885.     PyObject *value;
  886. {
  887.     PyObject *func;
  888.     PyObject *arg;
  889.     PyObject *res;
  890.  
  891.     if (value == NULL) {
  892.         if (delitemstr == NULL)
  893.             delitemstr = PyString_InternFromString("__delitem__");
  894.         func = instance_getattr(inst, delitemstr);
  895.     }
  896.     else {
  897.         if (setitemstr == NULL)
  898.             setitemstr = PyString_InternFromString("__setitem__");
  899.         func = instance_getattr(inst, setitemstr);
  900.     }
  901.     if (func == NULL)
  902.         return -1;
  903.     if (value == NULL)
  904.         arg = Py_BuildValue("(O)", key);
  905.     else
  906.         arg = Py_BuildValue("(OO)", key, value);
  907.     if (arg == NULL) {
  908.         Py_DECREF(func);
  909.         return -1;
  910.     }
  911.     res = PyEval_CallObject(func, arg);
  912.     Py_DECREF(func);
  913.     Py_DECREF(arg);
  914.     if (res == NULL)
  915.         return -1;
  916.     Py_DECREF(res);
  917.     return 0;
  918. }
  919.  
  920. static PyMappingMethods instance_as_mapping = {
  921.     (inquiry)instance_length, /*mp_length*/
  922.     (binaryfunc)instance_subscript, /*mp_subscript*/
  923.     (objobjargproc)instance_ass_subscript, /*mp_ass_subscript*/
  924. };
  925.  
  926. static PyObject *
  927. instance_item(inst, i)
  928.     PyInstanceObject *inst;
  929.     int i;
  930. {
  931.     PyObject *func, *arg, *res;
  932.  
  933.     if (getitemstr == NULL)
  934.         getitemstr = PyString_InternFromString("__getitem__");
  935.     func = instance_getattr(inst, getitemstr);
  936.     if (func == NULL)
  937.         return NULL;
  938.     arg = Py_BuildValue("(i)", i);
  939.     if (arg == NULL) {
  940.         Py_DECREF(func);
  941.         return NULL;
  942.     }
  943.     res = PyEval_CallObject(func, arg);
  944.     Py_DECREF(func);
  945.     Py_DECREF(arg);
  946.     return res;
  947. }
  948.  
  949. static PyObject *
  950. instance_slice(inst, i, j)
  951.     PyInstanceObject *inst;
  952.     int i, j;
  953. {
  954.     PyObject *func, *arg, *res;
  955.     static PyObject *getslicestr;
  956.  
  957.     if (getslicestr == NULL)
  958.         getslicestr = PyString_InternFromString("__getslice__");
  959.     func = instance_getattr(inst, getslicestr);
  960.     if (func == NULL)
  961.         return NULL;
  962.     arg = Py_BuildValue("(ii)", i, j);
  963.     if (arg == NULL) {
  964.         Py_DECREF(func);
  965.         return NULL;
  966.     }
  967.     res = PyEval_CallObject(func, arg);
  968.     Py_DECREF(func);
  969.     Py_DECREF(arg);
  970.     return res;
  971. }
  972.  
  973. static int
  974. instance_ass_item(inst, i, item)
  975.     PyInstanceObject *inst;
  976.     int i;
  977.     PyObject *item;
  978. {
  979.     PyObject *func, *arg, *res;
  980.  
  981.     if (item == NULL) {
  982.         if (delitemstr == NULL)
  983.             delitemstr = PyString_InternFromString("__delitem__");
  984.         func = instance_getattr(inst, delitemstr);
  985.     }
  986.     else {
  987.         if (setitemstr == NULL)
  988.             setitemstr = PyString_InternFromString("__setitem__");
  989.         func = instance_getattr(inst, setitemstr);
  990.     }
  991.     if (func == NULL)
  992.         return -1;
  993.     if (item == NULL)
  994.         arg = Py_BuildValue("i", i);
  995.     else
  996.         arg = Py_BuildValue("(iO)", i, item);
  997.     if (arg == NULL) {
  998.         Py_DECREF(func);
  999.         return -1;
  1000.     }
  1001.     res = PyEval_CallObject(func, arg);
  1002.     Py_DECREF(func);
  1003.     Py_DECREF(arg);
  1004.     if (res == NULL)
  1005.         return -1;
  1006.     Py_DECREF(res);
  1007.     return 0;
  1008. }
  1009.  
  1010. static int
  1011. instance_ass_slice(inst, i, j, value)
  1012.     PyInstanceObject *inst;
  1013.     int i, j;
  1014.     PyObject *value;
  1015. {
  1016.     PyObject *func, *arg, *res;
  1017.     static PyObject *setslicestr, *delslicestr;
  1018.  
  1019.     if (value == NULL) {
  1020.         if (delslicestr == NULL)
  1021.             delslicestr =
  1022.                 PyString_InternFromString("__delslice__");
  1023.         func = instance_getattr(inst, delslicestr);
  1024.     }
  1025.     else {
  1026.         if (setslicestr == NULL)
  1027.             setslicestr =
  1028.                 PyString_InternFromString("__setslice__");
  1029.         func = instance_getattr(inst, setslicestr);
  1030.     }
  1031.     if (func == NULL)
  1032.         return -1;
  1033.     if (value == NULL)
  1034.         arg = Py_BuildValue("(ii)", i, j);
  1035.     else
  1036.         arg = Py_BuildValue("(iiO)", i, j, value);
  1037.     if (arg == NULL) {
  1038.         Py_DECREF(func);
  1039.         return -1;
  1040.     }
  1041.     res = PyEval_CallObject(func, arg);
  1042.     Py_DECREF(func);
  1043.     Py_DECREF(arg);
  1044.     if (res == NULL)
  1045.         return -1;
  1046.     Py_DECREF(res);
  1047.     return 0;
  1048. }
  1049.  
  1050. static int instance_contains(PyInstanceObject *inst, PyObject *member)
  1051. {
  1052.     static PyObject *__contains__;
  1053.     PyObject *func, *arg, *res;
  1054.     int ret;
  1055.  
  1056.     if(__contains__ == NULL) {
  1057.         __contains__ = PyString_InternFromString("__contains__");
  1058.         if(__contains__ == NULL)
  1059.             return -1;
  1060.     }
  1061.     func = instance_getattr(inst, __contains__);
  1062.     if(func == NULL) {
  1063.         /* fall back to previous behaviour */
  1064.         int i, cmp_res;
  1065.  
  1066.         if(!PyErr_ExceptionMatches(PyExc_AttributeError))
  1067.             return -1;
  1068.         PyErr_Clear();
  1069.         for(i=0;;i++) {
  1070.             PyObject *obj = instance_item(inst, i);
  1071.             int ret = 0;
  1072.  
  1073.             if(obj == NULL) {
  1074.                 if(!PyErr_ExceptionMatches(PyExc_IndexError))
  1075.                     return -1;
  1076.                 PyErr_Clear();
  1077.                 return 0;
  1078.             }
  1079.             if(PyObject_Cmp(obj, member, &cmp_res) == -1)
  1080.                 ret = -1;
  1081.             if(cmp_res == 0) 
  1082.                 ret = 1;
  1083.             Py_DECREF(obj);
  1084.             if(ret)
  1085.                 return ret;
  1086.         }
  1087.     }
  1088.     arg = Py_BuildValue("(O)", member);
  1089.     if(arg == NULL) {
  1090.         Py_DECREF(func);
  1091.         return -1;
  1092.     }
  1093.     res = PyEval_CallObject(func, arg);
  1094.     Py_DECREF(func);
  1095.     Py_DECREF(arg);
  1096.     if(res == NULL) 
  1097.         return -1;
  1098.     ret = PyObject_IsTrue(res);
  1099.     Py_DECREF(res);
  1100.     return ret;
  1101. }
  1102.  
  1103. static PySequenceMethods instance_as_sequence = {
  1104.     (inquiry)instance_length, /*sq_length*/
  1105.     0, /*sq_concat*/
  1106.     0, /*sq_repeat*/
  1107.     (intargfunc)instance_item, /*sq_item*/
  1108.     (intintargfunc)instance_slice, /*sq_slice*/
  1109.     (intobjargproc)instance_ass_item, /*sq_ass_item*/
  1110.     (intintobjargproc)instance_ass_slice, /*sq_ass_slice*/
  1111.     (objobjproc)instance_contains, /* sq_contains */
  1112. };
  1113.  
  1114. static PyObject *
  1115. generic_unary_op(self, methodname)
  1116.     PyInstanceObject *self;
  1117.     PyObject *methodname;
  1118. {
  1119.     PyObject *func, *res;
  1120.  
  1121.     if ((func = instance_getattr(self, methodname)) == NULL)
  1122.         return NULL;
  1123.     res = PyEval_CallObject(func, (PyObject *)NULL);
  1124.     Py_DECREF(func);
  1125.     return res;
  1126. }
  1127.  
  1128.  
  1129. /* Forward */
  1130. static int halfbinop Py_PROTO((PyObject *, PyObject *, char *, PyObject **,
  1131.         PyObject * (*) Py_PROTO((PyObject *, PyObject *)), int ));
  1132.  
  1133.  
  1134. /* Implement a binary operator involving at least one class instance. */
  1135.  
  1136. PyObject *
  1137. PyInstance_DoBinOp(v, w, opname, ropname, thisfunc)
  1138.     PyObject *v;
  1139.     PyObject *w;
  1140.     char *opname;
  1141.     char *ropname;
  1142.     PyObject * (*thisfunc) Py_PROTO((PyObject *, PyObject *));
  1143. {
  1144.     char buf[256];
  1145.     PyObject *result = NULL;
  1146.     if (halfbinop(v, w, opname, &result, thisfunc, 0) <= 0)
  1147.         return result;
  1148.     if (halfbinop(w, v, ropname, &result, thisfunc, 1) <= 0)
  1149.         return result;
  1150.     /* Sigh -- special case for comnparisons */
  1151.     if (strcmp(opname, "__cmp__") == 0) {
  1152.         long c = (v < w) ? -1 : (v > w) ? 1 : 0;
  1153.         return PyInt_FromLong(c);
  1154.     }
  1155.     sprintf(buf, "%s nor %s defined for these operands", opname, ropname);
  1156.     PyErr_SetString(PyExc_TypeError, buf);
  1157.     return NULL;
  1158. }
  1159.  
  1160.  
  1161. /* Try one half of a binary operator involving a class instance.
  1162.    Return value:
  1163.    -1 if an exception is to be reported right away
  1164.    0  if we have a valid result
  1165.    1  if we could try another operation
  1166. */
  1167.  
  1168. static PyObject *coerce_obj;
  1169.  
  1170. static int
  1171. halfbinop(v, w, opname, r_result, thisfunc, swapped)
  1172.     PyObject *v;
  1173.     PyObject *w;
  1174.     char *opname;
  1175.     PyObject **r_result;
  1176.     PyObject * (*thisfunc) Py_PROTO((PyObject *, PyObject *));
  1177.     int swapped;
  1178. {
  1179.     PyObject *func;
  1180.     PyObject *args;
  1181.     PyObject *coercefunc;
  1182.     PyObject *coerced = NULL;
  1183.     PyObject *v1;
  1184.     
  1185.     if (!PyInstance_Check(v))
  1186.         return 1;
  1187.     if (coerce_obj == NULL) {
  1188.         coerce_obj = PyString_InternFromString("__coerce__");
  1189.         if (coerce_obj == NULL)
  1190.             return -1;
  1191.     }
  1192.     coercefunc = PyObject_GetAttr(v, coerce_obj);
  1193.     if (coercefunc == NULL) {
  1194.         PyErr_Clear();
  1195.     }
  1196.     else {
  1197.         args = Py_BuildValue("(O)", w);
  1198.         if (args == NULL) {
  1199.             return -1;
  1200.         }
  1201.         coerced = PyEval_CallObject(coercefunc, args);
  1202.         Py_DECREF(args);
  1203.         Py_DECREF(coercefunc);
  1204.         if (coerced == NULL) {
  1205.             return -1;
  1206.         }
  1207.         if (coerced == Py_None) {
  1208.             Py_DECREF(coerced);
  1209.             return 1;
  1210.         }
  1211.         if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
  1212.             Py_DECREF(coerced);
  1213.             PyErr_SetString(PyExc_TypeError,
  1214.                    "coercion should return None or 2-tuple");
  1215.             return -1;
  1216.         }
  1217.         v1 = PyTuple_GetItem(coerced, 0);
  1218.         w = PyTuple_GetItem(coerced, 1);
  1219.         if (v1 != v) {
  1220.             v = v1;
  1221.             if (!PyInstance_Check(v) && !PyInstance_Check(w)) {
  1222.                 if (swapped)
  1223.                     *r_result = (*thisfunc)(w, v);
  1224.                 else
  1225.                     *r_result = (*thisfunc)(v, w);
  1226.                 Py_DECREF(coerced);
  1227.                 return *r_result == NULL ? -1 : 0;
  1228.             }
  1229.         }
  1230.     }
  1231.     func = PyObject_GetAttrString(v, opname);
  1232.     if (func == NULL) {
  1233.         Py_XDECREF(coerced);
  1234.         if (!PyErr_ExceptionMatches(PyExc_AttributeError))
  1235.             return -1;
  1236.         PyErr_Clear();
  1237.         return 1;
  1238.     }
  1239.     args = Py_BuildValue("(O)", w);
  1240.     if (args == NULL) {
  1241.         Py_DECREF(func);
  1242.         Py_XDECREF(coerced);
  1243.         return -1;
  1244.     }
  1245.     *r_result = PyEval_CallObject(func, args);
  1246.     Py_DECREF(args);
  1247.     Py_DECREF(func);
  1248.     Py_XDECREF(coerced);
  1249.     return *r_result == NULL ? -1 : 0;
  1250. }
  1251.  
  1252. static int
  1253. instance_coerce(pv, pw)
  1254.     PyObject **pv;
  1255.     PyObject **pw;
  1256. {
  1257.     PyObject *v = *pv;
  1258.     PyObject *w = *pw;
  1259.     PyObject *coercefunc;
  1260.     PyObject *args;
  1261.     PyObject *coerced;
  1262.  
  1263.     if (coerce_obj == NULL) {
  1264.         coerce_obj = PyString_InternFromString("__coerce__");
  1265.         if (coerce_obj == NULL)
  1266.             return -1;
  1267.     }
  1268.     coercefunc = PyObject_GetAttr(v, coerce_obj);
  1269.     if (coercefunc == NULL) {
  1270.         /* No __coerce__ method: always OK */
  1271.         PyErr_Clear();
  1272.         Py_INCREF(v);
  1273.         Py_INCREF(w);
  1274.         return 0;
  1275.     }
  1276.     /* Has __coerce__ method: call it */
  1277.     args = Py_BuildValue("(O)", w);
  1278.     if (args == NULL) {
  1279.         return -1;
  1280.     }
  1281.     coerced = PyEval_CallObject(coercefunc, args);
  1282.     Py_DECREF(args);
  1283.     Py_DECREF(coercefunc);
  1284.     if (coerced == NULL) {
  1285.         /* __coerce__ call raised an exception */
  1286.         return -1;
  1287.     }
  1288.     if (coerced == Py_None) {
  1289.         /* __coerce__ says "I can't do it" */
  1290.         Py_DECREF(coerced);
  1291.         return 1;
  1292.     }
  1293.     if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
  1294.         /* __coerce__ return value is malformed */
  1295.         Py_DECREF(coerced);
  1296.         PyErr_SetString(PyExc_TypeError,
  1297.                "coercion should return None or 2-tuple");
  1298.         return -1;
  1299.     }
  1300.     /* __coerce__ returned two new values */
  1301.     *pv = PyTuple_GetItem(coerced, 0);
  1302.     *pw = PyTuple_GetItem(coerced, 1);
  1303.     Py_INCREF(*pv);
  1304.     Py_INCREF(*pw);
  1305.     Py_DECREF(coerced);
  1306.     return 0;
  1307. }
  1308.  
  1309.  
  1310. #ifdef __SASC
  1311. #define UNARY(funcname, methodname) \
  1312. static PyObject *funcname(PyInstanceObject *self) { \
  1313.     static PyObject *o; \
  1314.     if (o == NULL) o = PyString_InternFromString(methodname); \
  1315.     return generic_unary_op(self, o); \
  1316. }
  1317. #else /* !__SASC */
  1318. #define UNARY(funcname, methodname) \
  1319. static PyObject *funcname(self) PyInstanceObject *self; { \
  1320.     static PyObject *o; \
  1321.     if (o == NULL) o = PyString_InternFromString(methodname); \
  1322.     return generic_unary_op(self, o); \
  1323. }
  1324. #endif
  1325.  
  1326. UNARY(instance_neg, "__neg__")
  1327. UNARY(instance_pos, "__pos__")
  1328. UNARY(instance_abs, "__abs__")
  1329.  
  1330. static int
  1331. instance_nonzero(self)
  1332.     PyInstanceObject *self;
  1333. {
  1334.     PyObject *func, *res;
  1335.     long outcome;
  1336.     static PyObject *nonzerostr;
  1337.  
  1338.     if (nonzerostr == NULL)
  1339.         nonzerostr = PyString_InternFromString("__nonzero__");
  1340.     if ((func = instance_getattr(self, nonzerostr)) == NULL) {
  1341.         PyErr_Clear();
  1342.         if (lenstr == NULL)
  1343.             lenstr = PyString_InternFromString("__len__");
  1344.         if ((func = instance_getattr(self, lenstr)) == NULL) {
  1345.             PyErr_Clear();
  1346.             /* Fall back to the default behavior:
  1347.                all instances are nonzero */
  1348.             return 1;
  1349.         }
  1350.     }
  1351.     res = PyEval_CallObject(func, (PyObject *)NULL);
  1352.     Py_DECREF(func);
  1353.     if (res == NULL)
  1354.         return -1;
  1355.     if (!PyInt_Check(res)) {
  1356.         Py_DECREF(res);
  1357.         PyErr_SetString(PyExc_TypeError,
  1358.                 "__nonzero__ should return an int");
  1359.         return -1;
  1360.     }
  1361.     outcome = PyInt_AsLong(res);
  1362.     Py_DECREF(res);
  1363.     if (outcome < 0) {
  1364.         PyErr_SetString(PyExc_ValueError,
  1365.                 "__nonzero__ should return >= 0");
  1366.         return -1;
  1367.     }
  1368.     return outcome > 0;
  1369. }
  1370.  
  1371. UNARY(instance_invert, "__invert__")
  1372. UNARY(instance_int, "__int__")
  1373. UNARY(instance_long, "__long__")
  1374. UNARY(instance_float, "__float__")
  1375. UNARY(instance_oct, "__oct__")
  1376. UNARY(instance_hex, "__hex__")
  1377.  
  1378. /* This version is for ternary calls only (z != None) */
  1379. static PyObject *
  1380. instance_pow(v, w, z)
  1381.     PyObject *v;
  1382.     PyObject *w;
  1383.     PyObject *z;
  1384. {
  1385.     /* XXX Doesn't do coercions... */
  1386.     PyObject *func;
  1387.     PyObject *args;
  1388.     PyObject *result;
  1389.     static PyObject *powstr;
  1390.  
  1391.     if (powstr == NULL)
  1392.         powstr = PyString_InternFromString("__pow__");
  1393.     func = PyObject_GetAttr(v, powstr);
  1394.     if (func == NULL)
  1395.         return NULL;
  1396.     args = Py_BuildValue("(OO)", w, z);
  1397.     if (args == NULL) {
  1398.         Py_DECREF(func);
  1399.         return NULL;
  1400.     }
  1401.     result = PyEval_CallObject(func, args);
  1402.     Py_DECREF(func);
  1403.     Py_DECREF(args);
  1404.     return result;
  1405. }
  1406.  
  1407. static PyNumberMethods instance_as_number = {
  1408.     0, /*nb_add*/
  1409.     0, /*nb_subtract*/
  1410.     0, /*nb_multiply*/
  1411.     0, /*nb_divide*/
  1412.     0, /*nb_remainder*/
  1413.     0, /*nb_divmod*/
  1414.     (ternaryfunc)instance_pow, /*nb_power*/
  1415.     (unaryfunc)instance_neg, /*nb_negative*/
  1416.     (unaryfunc)instance_pos, /*nb_positive*/
  1417.     (unaryfunc)instance_abs, /*nb_absolute*/
  1418.     (inquiry)instance_nonzero, /*nb_nonzero*/
  1419.     (unaryfunc)instance_invert, /*nb_invert*/
  1420.     0, /*nb_lshift*/
  1421.     0, /*nb_rshift*/
  1422.     0, /*nb_and*/
  1423.     0, /*nb_xor*/
  1424.     0, /*nb_or*/
  1425.     (coercion)instance_coerce, /*nb_coerce*/
  1426.     (unaryfunc)instance_int, /*nb_int*/
  1427.     (unaryfunc)instance_long, /*nb_long*/
  1428.     (unaryfunc)instance_float, /*nb_float*/
  1429.     (unaryfunc)instance_oct, /*nb_oct*/
  1430.     (unaryfunc)instance_hex, /*nb_hex*/
  1431. };
  1432.  
  1433. PyTypeObject PyInstance_Type = {
  1434.     PyObject_HEAD_INIT(&PyType_Type)
  1435.     0,
  1436.     "instance",
  1437.     sizeof(PyInstanceObject),
  1438.     0,
  1439.     (destructor)instance_dealloc, /*tp_dealloc*/
  1440.     0,            /*tp_print*/
  1441.     0,            /*tp_getattr*/
  1442.     0,            /*tp_setattr*/
  1443.     instance_compare,    /*tp_compare*/
  1444.     (reprfunc)instance_repr, /*tp_repr*/
  1445.     &instance_as_number,    /*tp_as_number*/
  1446.     &instance_as_sequence,    /*tp_as_sequence*/
  1447.     &instance_as_mapping,    /*tp_as_mapping*/
  1448.     (hashfunc)instance_hash, /*tp_hash*/
  1449.     0,            /*tp_call*/
  1450.     0,            /*tp_str*/
  1451.     (getattrofunc)instance_getattr, /*tp_getattro*/
  1452.     (setattrofunc)instance_setattr, /*tp_setattro*/
  1453.         0, /* tp_as_buffer */
  1454.     Py_TPFLAGS_DEFAULT, /*tp_flags */
  1455. };
  1456.  
  1457.  
  1458. /* Instance method objects are used for two purposes:
  1459.    (a) as bound instance methods (returned by instancename.methodname)
  1460.    (b) as unbound methods (returned by ClassName.methodname)
  1461.    In case (b), im_self is NULL
  1462. */
  1463.  
  1464. static PyMethodObject *free_list;
  1465.  
  1466. PyObject *
  1467. PyMethod_New(func, self, class)
  1468.     PyObject *func;
  1469.     PyObject *self;
  1470.     PyObject *class;
  1471. {
  1472.     register PyMethodObject *im;
  1473.     if (!PyCallable_Check(func)) {
  1474.         PyErr_BadInternalCall();
  1475.         return NULL;
  1476.     }
  1477.     im = free_list;
  1478.     if (im != NULL) {
  1479.         free_list = (PyMethodObject *)(im->im_self);
  1480.         PyObject_INIT(im, &PyMethod_Type);
  1481.     }
  1482.     else {
  1483.         im = PyObject_NEW(PyMethodObject, &PyMethod_Type);
  1484.         if (im == NULL)
  1485.             return NULL;
  1486.     }
  1487.     Py_INCREF(func);
  1488.     im->im_func = func;
  1489.     Py_XINCREF(self);
  1490.     im->im_self = self;
  1491.     Py_INCREF(class);
  1492.     im->im_class = class;
  1493.     return (PyObject *)im;
  1494. }
  1495.  
  1496. PyObject *
  1497. PyMethod_Function(im)
  1498.     register PyObject *im;
  1499. {
  1500.     if (!PyMethod_Check(im)) {
  1501.         PyErr_BadInternalCall();
  1502.         return NULL;
  1503.     }
  1504.     return ((PyMethodObject *)im)->im_func;
  1505. }
  1506.  
  1507. PyObject *
  1508. PyMethod_Self(im)
  1509.     register PyObject *im;
  1510. {
  1511.     if (!PyMethod_Check(im)) {
  1512.         PyErr_BadInternalCall();
  1513.         return NULL;
  1514.     }
  1515.     return ((PyMethodObject *)im)->im_self;
  1516. }
  1517.  
  1518. PyObject *
  1519. PyMethod_Class(im)
  1520.     register PyObject *im;
  1521. {
  1522.     if (!PyMethod_Check(im)) {
  1523.         PyErr_BadInternalCall();
  1524.         return NULL;
  1525.     }
  1526.     return ((PyMethodObject *)im)->im_class;
  1527. }
  1528.  
  1529. /* Class method methods */
  1530.  
  1531. #define OFF(x) offsetof(PyMethodObject, x)
  1532.  
  1533. static struct memberlist instancemethod_memberlist[] = {
  1534.     {"im_func",    T_OBJECT,    OFF(im_func)},
  1535.     {"im_self",    T_OBJECT,    OFF(im_self)},
  1536.     {"im_class",    T_OBJECT,    OFF(im_class)},
  1537.     /* Dummies that are not handled by getattr() except for __members__ */
  1538.     {"__doc__",    T_INT,        0},
  1539.     {"__name__",    T_INT,        0},
  1540.     {NULL}    /* Sentinel */
  1541. };
  1542.  
  1543. static PyObject *
  1544. instancemethod_getattr(im, name)
  1545.     register PyMethodObject *im;
  1546.     PyObject *name;
  1547. {
  1548.     char *sname = PyString_AsString(name);
  1549.     if (sname[0] == '_') {
  1550.         /* Inherit __name__ and __doc__ from the callable object
  1551.            implementing the method */
  1552.             if (strcmp(sname, "__name__") == 0 ||
  1553.             strcmp(sname, "__doc__") == 0)
  1554.             return PyObject_GetAttr(im->im_func, name);
  1555.     }
  1556.     if (PyEval_GetRestricted()) {
  1557.         PyErr_SetString(PyExc_RuntimeError,
  1558.         "instance-method attributes not accessible in restricted mode");
  1559.         return NULL;
  1560.     }
  1561.     return PyMember_Get((char *)im, instancemethod_memberlist, sname);
  1562. }
  1563.  
  1564. static void
  1565. instancemethod_dealloc(im)
  1566.     register PyMethodObject *im;
  1567. {
  1568.     Py_DECREF(im->im_func);
  1569.     Py_XDECREF(im->im_self);
  1570.     Py_DECREF(im->im_class);
  1571.     im->im_self = (PyObject *)free_list;
  1572.     free_list = im;
  1573. }
  1574.  
  1575. static int
  1576. instancemethod_compare(a, b)
  1577.     PyMethodObject *a, *b;
  1578. {
  1579.     if (a->im_self != b->im_self)
  1580.         return (a->im_self < b->im_self) ? -1 : 1;
  1581.     return PyObject_Compare(a->im_func, b->im_func);
  1582. }
  1583.  
  1584. static PyObject *
  1585. instancemethod_repr(a)
  1586.     PyMethodObject *a;
  1587. {
  1588.     char buf[240];
  1589.     PyInstanceObject *self = (PyInstanceObject *)(a->im_self);
  1590.     PyObject *func = a->im_func;
  1591.     PyClassObject *class = (PyClassObject *)(a->im_class);
  1592.     PyObject *fclassname, *iclassname, *funcname;
  1593.     char *fcname, *icname, *fname;
  1594.     fclassname = class->cl_name;
  1595.     if (PyFunction_Check(func)) {
  1596.         funcname = ((PyFunctionObject *)func)->func_name;
  1597.         Py_INCREF(funcname);
  1598.     }
  1599.     else {
  1600.         funcname = PyObject_GetAttrString(func,"__name__");
  1601.         if (funcname == NULL)
  1602.             PyErr_Clear();
  1603.     }
  1604.     if (funcname != NULL && PyString_Check(funcname))
  1605.         fname = PyString_AS_STRING(funcname);
  1606.     else
  1607.         fname = "?";
  1608.     if (fclassname != NULL && PyString_Check(fclassname))
  1609.         fcname = PyString_AsString(fclassname);
  1610.     else
  1611.         fcname = "?";
  1612.     if (self == NULL)
  1613.         sprintf(buf, "<unbound method %.100s.%.100s>", fcname, fname);
  1614.     else {
  1615.         iclassname = self->in_class->cl_name;
  1616.         if (iclassname != NULL && PyString_Check(iclassname))
  1617.             icname = PyString_AsString(iclassname);
  1618.         else
  1619.             icname = "?";
  1620.         sprintf(buf, "<method %.60s.%.60s of %.60s instance at %lx>",
  1621.             fcname, fname, icname, (long)self);
  1622.     }
  1623.     Py_XDECREF(funcname);
  1624.     return PyString_FromString(buf);
  1625. }
  1626.  
  1627. static long
  1628. instancemethod_hash(a)
  1629.     PyMethodObject *a;
  1630. {
  1631.     long x, y;
  1632.     if (a->im_self == NULL)
  1633.         x = PyObject_Hash(Py_None);
  1634.     else
  1635.         x = PyObject_Hash(a->im_self);
  1636.     if (x == -1)
  1637.         return -1;
  1638.     y = PyObject_Hash(a->im_func);
  1639.     if (y == -1)
  1640.         return -1;
  1641.     return x ^ y;
  1642. }
  1643.  
  1644. PyTypeObject PyMethod_Type = {
  1645.     PyObject_HEAD_INIT(&PyType_Type)
  1646.     0,
  1647.     "instance method",
  1648.     sizeof(PyMethodObject),
  1649.     0,
  1650.     (destructor)instancemethod_dealloc, /*tp_dealloc*/
  1651.     0,            /*tp_print*/
  1652.     0,            /*tp_getattr*/
  1653.     0,            /*tp_setattr*/
  1654.     (cmpfunc)instancemethod_compare, /*tp_compare*/
  1655.     (reprfunc)instancemethod_repr, /*tp_repr*/
  1656.     0,            /*tp_as_number*/
  1657.     0,            /*tp_as_sequence*/
  1658.     0,            /*tp_as_mapping*/
  1659.     (hashfunc)instancemethod_hash, /*tp_hash*/
  1660.     0,            /*tp_call*/
  1661.     0,            /*tp_str*/
  1662.     (getattrofunc)instancemethod_getattr, /*tp_getattro*/
  1663.     0,            /*tp_setattro*/
  1664. };
  1665.  
  1666. /* Clear out the free list */
  1667.  
  1668. void
  1669. PyMethod_Fini()
  1670. {
  1671.     while (free_list) {
  1672.         PyMethodObject *im = free_list;
  1673.         free_list = (PyMethodObject *)(im->im_self);
  1674.         PyObject_DEL(im);
  1675.     }
  1676. }
  1677.